import { STORAGE_KEYS } from "@/config";

/**
 * 从localStorage获取数据
 */
export const getItem = (key: string) => {
  const value = sessionStorage.getItem(key);
  if (!value) return null;
  try {
    return JSON.parse(value);
  } catch {
    return value;
  }
};

/**
 * 将数据存储到localStorage
 */
export const setItem = (key: string, value: any) => {
  if (typeof value === "object") {
    value = JSON.stringify(value);
  }
  sessionStorage.setItem(key, value);
};

/**
 * 从localStorage删除数据
 */
export const removeItem = (key: string) => {
  sessionStorage.removeItem(key);
};

/**
 * 检查token是否有效
 */
export const isTokenValid = (token: string): boolean => {
  try {
    const base64Url = token.split(".")[1];
    const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
    const payload = JSON.parse(window.atob(base64));
    const exp = payload.exp * 1000; // 转换为毫秒
    return exp > Date.now();
  } catch {
    return false;
  }
};

/**
 * 清除所有存储的数据
 */
export const clearStorage = () => {
  sessionStorage.clear();
};
